package com.rede.didiok.user.modulelist.rank.service.impl;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rede.didiok.common.constant.conf.MessageConf;
import com.rede.didiok.common.constant.conf.RedisConf;
import com.rede.didiok.common.constant.conf.SQLConf;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.dto.rank.MemberTagDto;
import com.rede.didiok.common.enums.PublishEnum;
import com.rede.didiok.common.enums.StatusEnum;
import com.rede.didiok.common.utils.*;
import com.rede.didiok.user.modulelist.rank.dao.MemberTagDao;
import com.rede.didiok.user.modulelist.rank.entity.MemberTagEntity;
import com.rede.didiok.user.modulelist.rank.entity.RankMemberEntity;
import com.rede.didiok.user.modulelist.rank.service.MemberTagService;
import com.rede.didiok.user.modulelist.rank.service.RankMemberService;


@Service("rankTagService")
public class MemberTagServiceImpl extends ServiceImpl<MemberTagDao, MemberTagEntity> implements MemberTagService {
    @Autowired
    private RankMemberService rankMemberService;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberTagEntity> page = this.page(
                new Query<MemberTagEntity>().getPage(params),
                new QueryWrapper<MemberTagEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public IPage<MemberTagEntity> getPageList(MemberTagDto tagDto) {
        QueryWrapper<MemberTagEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(tagDto.getKeyword()) && !StringUtils.isEmpty(tagDto.getKeyword())) {
            queryWrapper.like(SQLConf.TAG_NAME, tagDto.getKeyword().trim());
        }

        Page<MemberTagEntity> page = new Page<>();
        page.setCurrent(tagDto.getCurrentPage());
        page.setSize(tagDto.getPageSize());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        if (StringUtils.isNotEmpty(tagDto.getOrderByAscColumn())) {
            // 将驼峰转换成下划线
            String column = StringUtils.underLine(new StringBuffer(tagDto.getOrderByAscColumn())).toString();
            queryWrapper.orderByAsc(column);
        } else if (StringUtils.isNotEmpty(tagDto.getOrderByDescColumn())) {
            // 将驼峰转换成下划线
            String column = StringUtils.underLine(new StringBuffer(tagDto.getOrderByDescColumn())).toString();
            queryWrapper.orderByDesc(column);
        } else {
            queryWrapper.orderByDesc(SQLConf.SORT);
        }
        IPage<MemberTagEntity> pageList = this.page(page, queryWrapper);
        return pageList;
    }

    @Override
    public List<MemberTagEntity> getList() {
        QueryWrapper<MemberTagEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SysConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        List<MemberTagEntity> tagList = this.list(queryWrapper);
        return tagList;
    }

    @Override
    public String addTag(MemberTagDto tagVO) {
        QueryWrapper<MemberTagEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.TAG_NAME, tagVO.getTagName());
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        MemberTagEntity tempTag = this.getOne(queryWrapper);
        if (tempTag != null) {
            return ResultUtil.errorWithMessage(MessageConf.ENTITY_EXIST);
        }
        MemberTagEntity tag = new MemberTagEntity();
        tag.setTagName(tagVO.getTagName());
        tag.setStatus(StatusEnum.ENABLE);
        tag.setSort(tagVO.getSort());
        tag.insert();
        // 删除Redis中的BLOG_TAG
        deleteRedisBlogTagList();
        return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
    }

    @Override
    public String editTag(MemberTagDto tagDto) {
        MemberTagEntity tag = this.getById(tagDto.getUid());

        if (tag != null && !tag.getTagName().equals(tagDto.getTagName())) {
            QueryWrapper<MemberTagEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(SQLConf.TAG_NAME, tagDto.getTagName());
            queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
            MemberTagEntity tempTag = this.getOne(queryWrapper);
            if (tempTag != null) {
                return ResultUtil.errorWithMessage(MessageConf.ENTITY_EXIST);
            }
        }

        tag.setTagName(tagDto.getTagName());
        tag.setStatus(StatusEnum.ENABLE);
        tag.setSort(tagDto.getSort());
        tag.setUpdateTime(new Date());
        tag.updateById();
        // 删除和标签相关的博客缓存
        rankMemberService.deleteRedisByMemberTag();
        // 删除Redis中的BLOG_TAG
        deleteRedisBlogTagList();
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    @Override
    public String deleteBatchTag(List<MemberTagDto> tagDtoList) {
        if (tagDtoList.size() <= 0) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        List<String> uids = new ArrayList<>();
        tagDtoList.forEach(item -> {
            uids.add(item.getUid());
        });

        // 判断要删除的分类，是否有博客
        QueryWrapper<RankMemberEntity> blogQueryWrapper = new QueryWrapper<>();
        blogQueryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        blogQueryWrapper.in(SQLConf.TAG_UID, uids);
        Integer blogCount = rankMemberService.count(blogQueryWrapper);
        if (blogCount > 0) {
            return ResultUtil.errorWithMessage(MessageConf.MEMBER_UNDER_THIS_TAG);
        }

        Collection<MemberTagEntity> tagList = this.listByIds(uids);

        tagList.forEach(item -> {
            item.setUpdateTime(new Date());
            item.setStatus(StatusEnum.DISABLED);
        });

        Boolean save = this.updateBatchById(tagList);
        // 删除和标签相关的博客缓存
        rankMemberService.deleteRedisByMemberTag();
        // 删除Redis中的BLOG_TAG
        deleteRedisBlogTagList();
        if (save) {
            return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS);
        } else {
            return ResultUtil.errorWithMessage(MessageConf.DELETE_FAIL);
        }
    }

    @Override
    public String stickTag(MemberTagDto tagDto) {
        MemberTagEntity tag = this.getById(tagDto.getUid());

        //查找出最大的那一个
        QueryWrapper<MemberTagEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(SQLConf.SORT);
        Page<MemberTagEntity> page = new Page<>();
        page.setCurrent(0);
        page.setSize(1);
        IPage<MemberTagEntity> pageList = this.page(page, queryWrapper);
        List<MemberTagEntity> list = pageList.getRecords();
        MemberTagEntity maxTag = list.get(0);

        if (StringUtils.isEmpty(maxTag.getUid())) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        if (maxTag.getUid().equals(tag.getUid())) {
            return ResultUtil.errorWithMessage(MessageConf.THIS_TAG_IS_TOP);
        }

        Integer sortCount = maxTag.getSort() + 1;

        tag.setSort(sortCount);
        tag.setUpdateTime(new Date());
        tag.updateById();
        // 删除Redis中的BLOG_TAG
        deleteRedisBlogTagList();
        return ResultUtil.successWithMessage(MessageConf.OPERATION_SUCCESS);
    }

    @Override
    public String tagSortByCite() {
        // 定义Map   key：tagUid,  value: 引用量
        Map<String, Integer> map = new HashMap<>();
        QueryWrapper<MemberTagEntity> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        List<MemberTagEntity> tagList = this.list(tagQueryWrapper);
        // 初始化所有标签的引用量
        tagList.forEach(item -> {
            map.put(item.getUid(), 0);
        });

        QueryWrapper<RankMemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.eq(SQLConf.IS_PUBLISH, PublishEnum.PUBLISH);
        // 过滤content字段
        queryWrapper.select(RankMemberEntity.class, i -> !i.getProperty().equals(SQLConf.CONTENT));
        List<RankMemberEntity> blogList = rankMemberService.list(queryWrapper);

        blogList.forEach(item -> {
            String tagUids = item.getTagUid();
            List<String> tagUidList = StringUtils.changeStringToString(tagUids, SysConf.FILE_SEGMENTATION);
            for (String tagUid : tagUidList) {
                if (map.get(tagUid) != null) {
                    Integer count = map.get(tagUid) + 1;
                    map.put(tagUid, count);
                } else {
                    map.put(tagUid, 0);
                }
            }
        });

        tagList.forEach(item -> {
            item.setSort(map.get(item.getUid()));
            item.setUpdateTime(new Date());
        });
        this.updateBatchById(tagList);
        // 删除Redis中的BLOG_TAG
        deleteRedisBlogTagList();
        return ResultUtil.successWithMessage(MessageConf.OPERATION_SUCCESS);
    }

    @Override
    public List<MemberTagEntity> getHotTag(Integer hotTagCount) {
        QueryWrapper<MemberTagEntity> queryWrapper = new QueryWrapper<>();
        Page<MemberTagEntity> page = new Page<>();
        page.setCurrent(1);
        page.setSize(hotTagCount);
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.orderByDesc(SQLConf.SORT);
        queryWrapper.orderByDesc(SQLConf.CLICK_COUNT);
        IPage<MemberTagEntity> pageList = this.page(page, queryWrapper);
        return pageList.getRecords();
    }

    @Override
    public MemberTagEntity getTopTag() {
        QueryWrapper<MemberTagEntity> tagQueryWrapper = new QueryWrapper<>();
        tagQueryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        tagQueryWrapper.last(SysConf.LIMIT_ONE);
        tagQueryWrapper.orderByDesc(SQLConf.SORT);
        MemberTagEntity tag = this.getOne(tagQueryWrapper);
        return tag;
    }

    /**
     * 删除Redis中的友链列表
     */
    private void deleteRedisBlogTagList() {
        // 删除Redis中的BLOG_LINK
        Set<String> keys = redisUtil.keys(RedisConf.MEMBER_TAG + Constants.SYMBOL_COLON + "*");
        redisUtil.delete(keys);
    }
}